package login_service_v1

import (
	"context"
	"log"
	"time"

	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"test.com/project-user/pkg/model"
	common "test.com/project-common"
	"test.com/project-common/logs"
	"test.com/project-user/pkg/dao"
	"test.com/project-user/pkg/repo"
	"test.com/project-common/errs"
)

type LoginService struct {
	UnimplementedLoginServiceServer,
	cache repo.Cache
}

// mustEmbedUnimplementedLoginServiceServer implements LoginServiceServer.
func (ls *LoginService) mustEmbedUnimplementedLoginServiceServer() {
	panic("unimplemented")
}

func New() *LoginService {
	return &LoginService{
		cache: dao.Rc,
	}
}

func (ls *LoginService) GetCaptcha(ctx context.Context, msg *CaptchaMessage) (*CaptchaResponse, error) {

	//获取参数
	mobile := msg.Mobile
	//校验参数
	if !common.VerifyMobile(mobile) {
		return nil,errs.GrpcError(model.NoLegalMobile)
	}

	//生成验证码(随机4位1000-9999 或者6位)
	code := "123456"

	//调用短信平台(三方 放入 go协程可以快速响应)

	go func() {
		time.Sleep(2 * time.Second)
		zap.L().Info("短信平台调用成功，发送短信 INFO")
		logs.LG.Debug("短信平台调用成功，发送短信 debug")
		zap.L().Error("短信平台调用成功，发送短信 error")
		//redis 后续缓存可能存在mysql当中 也可能存在mongo中 也可能存在memcache中
		//5 存储验证码 redis 当中 过期时间15分钟
		c, cancel := context.WithTimeout(context.Background(), 2*time.Second) //这个操作做多能操作多长时间
		defer cancel()
		err := ls.cache.Put(c, "REGISTER_"+mobile, code, 15*time.Minute)
		log.Printf("将手机号和验证码存入redis中 ：REGISTER_%s:%s/n", mobile, code)
		if err != nil {
			log.Println("验证码存入redis出错", err)
			return
		}
	}()
	return &CaptchaResponse{Code: code}, nil
}
func (LoginService) Register(context.Context, *RegisterMessage) (*RegisterResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method Register not implemented")
}
func (LoginService) Login(context.Context, *LoginMessage) (*LoginResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
}
func (LoginService) TokenVerify(context.Context, *LoginMessage) (*LoginResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method TokenVerify not implemented")
}
func (LoginService) MyOrgList(context.Context, *UserMessage) (*OrgListResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method MyOrgList not implemented")
}
func (LoginService) FindMemInfoById(context.Context, *UserMessage) (*MemberMessage, error) {
	return nil, status.Errorf(codes.Unimplemented, "method FindMemInfoById not implemented")
}
